<template>
    <div>
        <input type="file" id="fileInput" accept="application/pdf" v-show="false"></input>
        <el-button @click="handleOpenfileInput" type="primary">选择文件</el-button>
        <div id="viewer"></div>
        <!-- <embed type="application/pdf" width="100%" height="600px" src="https://static.wxb.com.cn/frontEnd/files/pdf/policy.pdf"></embed> -->
         <!-- <iframe src="https://static.wxb.com.cn/frontEnd/files/pdf/policy.pdf" width="100%" height="600px"></iframe> -->
    </div>
</template>

<script setup>
import { onMounted } from 'vue';
// 组件实现
import * as pdfjsLib from 'pdfjs-dist/webpack';

const handleOpenfileInput = () => {
    document.getElementById("fileInput").click();
};

const handleFileChange = async(event) => {
    const file = event.target.files[0];
    if (!file) return;
    // 渲染 PDF
    // const url = "https://static.wxb.com.cn/frontEnd/files/pdf/policy.pdf" //上传到oss的pdf文件地址
    const url = URL.createObjectURL(file); // 本地解析的pdf文件流生成的url
    const container = document.getElementById('viewer');
    try {
        const pdf = await pdfjsLib.getDocument(url).promise;
        for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) {
            pdf.getPage(pageNum).then(page => {
                const canvas = document.createElement('canvas');
                const context = canvas.getContext('2d');
                const viewport = page.getViewport({ scale: 1.5 });
                canvas.width = viewport.width;
                canvas.height = viewport.height;

                page.render({
                    canvasContext: context,
                    viewport: viewport
                });

                container.appendChild(canvas);
            });
        }
    } catch (error) {
        console.error('Error loading PDF:', error);
    }
};

onMounted(() => {
    document.getElementById("fileInput").addEventListener("change", async (event) => {
        handleFileChange(event)
    })
})
</script>
